package com.zhiwei.most.base.activitys

import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.SizeUtils
import com.zhiwei.most.R
import com.zhiwei.most.base.viewmodel.BaseViewModel
import com.zhiwei.most.ext.getVmClazz
import com.zhiwei.most.ext.notNull
import com.zhiwei.most.swipepanel.SwipePanel

/**
 * 作者　: hegaojian
 * 时间　: 2019/12/12
 * 描述　: ViewModelActivity基类，把ViewModel注入进来了
 */
abstract class BaseVmActivity<VM : BaseViewModel> : AppCompatActivity() {

    lateinit var mViewModel: VM

    private val onBackPressInterceptors = ArrayList<() -> Boolean>()

    abstract fun layoutId(): Int

    abstract fun initView(savedInstanceState: Bundle?)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initDataBind().notNull({
            setContentView(it)
        }, {
            setContentView(layoutId())
        })
        init(savedInstanceState)
    }

    private fun init(savedInstanceState: Bundle?) {
        mViewModel = createViewModel()
        initView(savedInstanceState)
        createObserver()
    }

    /**
     * 创建viewModel
     */
    private fun createViewModel(): VM {
        return ViewModelProvider(this).get(getVmClazz(this))
    }

    /**
     * 创建LiveData数据观察者
     */
    abstract fun createObserver()

    /**
     * 供子类BaseVmDbActivity 初始化Databinding操作
     */
    open fun initDataBind(): View? {
        return null
    }

    /**
     * 返回键事件
     * @param block 返回值表示是否拦截事件
     */
    fun onBackPressed(block: () -> Boolean) {
        onBackPressInterceptors.add(block)
    }

    override fun onBackPressed() {
        onBackPressInterceptors.forEach {
            if (it.invoke()) return
        }
        super.onBackPressed()
    }



}